<template>
  <div class="components-container" v-cloak>
    <sweet-modal ref="dialog" class="dialog" :sweetModalMaxWidth="pageWidth">
      <h3>{{title}}</h3>
      <div style="margin:10px 20px">
        <div class="layui-form-item">
          <div class="layui-inline">
                <label class="layui-form-label">汇总时间</label> 
                <div class="layui-input-inline">
                    <el-date-picker v-date type="date" v-model="regInfo.HSLSTARTDATE" readonly></el-date-picker>
                </div>
                <div class="layui-input-inline" style="width:15px;height:40px;line-height:40px;">
                    <p>至</p>
                </div>
                <div class="layui-input-inline">
                    <el-date-picker v-date type="date"  v-model="regInfo.HSLDATE" @change="QueryBaes" :readonly="!isbalance" :picker-options="pickerOptions1"></el-date-picker>
                </div>
          </div>
        </div>
        <div class="layui-form-item">
          <div class="layui-inline">
            <label class="layui-form-label">汇总描述</label>
            <div class="layui-input-inline">
              <el-input v-model="regInfo.HSLDESC" style="width:740px;" :readonly="!isbalance"></el-input>
            </div>
          </div>
        </div>
      </div>
      <div :style="{maxHeight:maxHeight+'px'}" style="overflow:auto;">
        <table class="layui-table" style="border-spacing: 0;">
          <colgroup>
            <col width="120">
            <col width="150">
            <col width="150">
            <col width="150">
            <col width="150">
            <col width="150">
            <col width="150">
            <col>
          </colgroup>
          <thead>
            <tr>
              <th>物品名称</th>
              <th>单位</th>
              <th>成本价(元)</th>
              <th>销售价(元)</th>
              <th>销售数量</th>
              <th>成本(元)</th>
              <th>销售金额(元)</th>
              <th>利润(元)</th>
            </tr>
          </thead>
          <tbody ref='inputs'>
            <tr class="allRow" v-for="(chl,index) in chlList">
              <td>
                <!-- 物品名称 -->
                {{chl.DPGNAME}}
              </td>
               <td>
                <!-- 单位 -->
                {{chl.DPGUNIT}}  
              </td>
              <td>
                <!-- 成本价 -->
                <!-- @blur="changebalance(chl,index)" -->
                <el-input @keyup.native="check(chl,index)" @input="Calculation(chl,$event,1)" :readonly="!isbalance"  @keydown.enter.native="enterEvent(index,3)" v-model="chl.HSHCOSTPRICE">
                  <!-- <template slot="append">件</template> -->
                </el-input>
              </td>
              <td>
                <!-- 销售价 --> 
                 <el-input @keyup.native="check(chl,index)" @input="Calculation(chl,$event,2)" :readonly="!isbalance" @keydown.enter.native="enterEvent(index,3)" v-model="chl.HSHSALEPRICE">
                  <!-- <template slot="append">件</template> -->
                </el-input>
              </td>
              <td>
                <!-- 销售数量 -->
                {{chl.HSHSALENUM}}
              </td>
              <td>
                <!-- 成本 -->
                <!-- :readonly="!isbalance" -->
                 <el-input @keyup.native="check(chl,index)" @keydown.enter.native="enterEvent(index,3)" :readonly="true" v-model="chl.HSHCOST">
                  <!-- <template slot="append">件</template> -->
                </el-input>
              </td>
              <td>
                <!-- 销售金额 -->
                <el-input @keyup.native="check(chl,index)" @keydown.enter.native="enterEvent(index,3)" :readonly="true" v-model="chl.HSHSALE">
                  <!-- <template slot="append">件</template> -->
                </el-input>
              </td>
               <td>
                <!-- 利润 -->
                 {{chl.HSHPROFIT}}
              </td>
            </tr>
          </tbody>
        </table>
      </div>
      <div class="layui-form-item btnCenter sweet-btn">
        <el-button @click="closeDialog">取消</el-button>
        <el-button type="primary" @click="submit()" :loading="this.$store.state.isloading" v-if="isbalance">保存</el-button>
      </div>
    </sweet-modal>

  </div>
</template>
<style rel="stylesheet/scss" lang="scss" scoped>
  @import "src/styles/common.scss";
  .el-button+.el-button {
    margin-left: 0;
  }

  .sweet-btn {
    margin-top: 20px;
  }

</style>

<script>
  import sweetModal from "@/components/sweetModal";
  import apiBase from "@/api/apiBase.js";
  import { formatDate, timeStringToDate } from "@/utils/date.js";
  import {
    accMul,
    Subtr,
    accAdd
  } from "@/utils/operations.js";
  import {
    ORDER
  } from "@/const/orderConst.js";
import Vue from 'vue';

  const INFO = '出库汇总详情';
  const ADD = "新增"; 

  export default {
    name: "hello",
    data() {
      return {
        pickerOptions1: {
          disabledDate(time) {
            return time.getTime() > new Date(new Date().getTime() - 24*60*60*1000);
          },
        },
        personality: null,
        pageWidth: 1200,
        maxHeight: 500,
        CHDID: null,
        order: null,
        title: null,
        //所有收费项目
        allCharge: [],
        chaList: [],
        payment: [],
        pointType: [],
        payData: {
          CHDCODNAME:'现金'
        },
        printUrl: null,
        printTitle: null,
        isHidden: null,
        //收费信息
        chdData: {},
        diechdData:[],
        dialogTableVisible:false,
        regInfo: {
            HSLUSR: null,//汇总人
            HSLSTARTDATE: null,//结存前时间
            HSLDATE: null,//结存后时间
            HSLDESC: null,//结存描述
        },
        //打印类型
        printName:null,
        //收费项目
        chlList: [
         
        ],
        chl: {
            DPGNAME: null,  //物品名称	
            DPGUNIT: null, //单位
            HSHCOSTPRICE: 0, //成本单价	  
            HSHSALEPRICE: 0, //销售单价	  
            HSHSALENUM: null, //销售数量	  
            HSHCOST: 0, //成本总价	  
            HSHSALE: 0, //销售总价	  
            HSHPROFIT: null, //利润
        },
        // 是否显示挂账按钮
        IsShowHangAccount: null,
        //区分详情和新增
        isbalance:true,
        StoragePosition: [],//存放位置
      };
    },
    methods: {
      //回车事件
      enterEvent(rowNum, colNum) {
        //获取所有行
        let rows = this.$refs.inputs.getElementsByClassName("allRow");
        //获取当前行
        let currow = rows[rowNum];
        // 获取当前行所有列
        let inputs = currow.getElementsByTagName("input");
        //强制隐藏下拉框
        if (colNum === 0) {
          let chl = this.chlList[rowNum];
          if (chl.CHLCHAID.length === 0) {
            this.$message({
              type: "error",
              message: `第${parseInt(rowNum) + 1}行收费项目不能为空!`
            });
            return;
          }
          let select = this.$refs.select;
          select[rowNum].visible = false;
        }
        //最后一列
        if (colNum === inputs.length - 1) {
          //最后一行
          if (rowNum === this.chlList.length - 1) {
           
          }
          //换行
          this.$nextTick(function () {
            this.enterEvent(rowNum + 1, -1);
          });
        } else {
          //获取下一个焦点
          this.$nextTick(function () {
            inputs[colNum + 1].select();
          });
        }
      },
      //打开弹出框
      open(order, id) {
        Object.assign(this.$data, this.$options.data());
        this.CHDID = id;
        this.order = order;
        switch (this.order) {
          case ADD:
            this.isbalance = true;
            this.title = "出库汇总新增";
            Object.assign(this.$data.regInfo, this.$options.data().regInfo);
            this.$refs.dialog.open();
            this.GetBalStartDate();//获取汇总时间
            break;
          case INFO:
            this.isbalance = false;
            this.title = "出库汇总详情";
            Object.assign(this.$data.regInfo, this.$options.data().regInfo);
            this.$refs.dialog.open();
            this.balanceInfo(id);
            break; 
          default:
            break;
        }
      },
      QueryBaes(){
       let data = {  
         HSLSTARTDATE: this.regInfo.HSLSTARTDATE,
         HSLDATE: this.regInfo.HSLDATE
       };
      data.HSLSTARTDATE = formatDate(
        data.HSLSTARTDATE,
        "yyyyMMdd"
      );
      data.HSLDATE = formatDate(
        data.HSLDATE,
        "yyyyMMdd"
      );
      if(this.title === "出库汇总新增"){
         data.HSLTYPE = "F";
       }
       apiBase.DoService(data, apiBase.getApiAdress().Depot.QueryAshHsl,res => {
         this.chlList = res.data.content;
         for(var i = 0;i < this.chlList.length;i++){
            this.chlList[i].isware = true;
            this.chlList[i].BALTHISBAL = Number(this.chlList[i].BALLASTBAL) + Number(this.chlList[i].BALTHISGETIN) - Number(this.chlList[i].BALTHISOUT);
            this.chlList[i].BALTAKEINVENTORY = 0;
            if(this.chlList[i].BALDEPOSIT === ""){
              this.chlList[i].isware = false;
            }else{
              this.chlList[i].isware = true;
            }
         }
         
       })
      },
    //计算金额
    Calculation(chl,val,num){
          if(num === 1){ //成本单价变动
            chl.HSHCOST = Number(val) * Number(chl.HSHSALENUM);
            chl.HSHPROFIT = Number(chl.HSHSALE) - Number(chl.HSHCOST); 
          }else if(num === 2){ //销售单价变动
            chl.HSHSALE = Number(val) * Number(chl.HSHSALENUM);
            chl.HSHPROFIT = Number(chl.HSHSALE) - Number(chl.HSHCOST); 
          }
      },
    // 出库汇总物品详情
    QueryBae(){
       let data = {};
       if(this.title === "出库汇总新增"){
         data.HSLTYPE = "F";
       }
      data.HSLSTARTDATE = formatDate(
        this.regInfo.HSLSTARTDATE,
        "yyyyMMdd"
      );
      data.HSLDATE = formatDate(
        this.regInfo.HSLDATE,
        "yyyyMMdd"
      );
       apiBase.DoService(data, apiBase.getApiAdress().Depot.QueryAshHsl,res => {   
         this.chlList = res.data.content;
       })
     },
     //详情
     balanceInfo(id){
        let data = {
          HSLID: id
        }
        apiBase.DoService(data, apiBase.getApiAdress().Depot.DetailAshHsl, res => {
         this.chlList = res.data.content.list_Hsh;
         this.regInfo.HSLDATE = res.data.content.HSLDATE;
         this.regInfo.HSLSTARTDATE = res.data.content.HSLSTARTDATE;
         this.regInfo.HSLDESC = res.data.content.HSLDESC;
         for(var i = 0;i < this.chlList.length;i++){
           this.chlList[i].isware = true;
         }
        })
     },
     //获取出库汇总起始日期
     GetBalStartDate(){
        let data = {};
        if(this.title === "出库汇总新增"){
          data.HSLTYPE = "F";
        }
       apiBase.DoService(data, apiBase.getApiAdress().Depot.GetAshHslStartDate, res => {
         this.regInfo.HSLSTARTDATE = res.data.content.StartDate;
        this.regInfo.HSLDATE = new Date(new Date().getTime() - 24*60*60*1000);
        this.QueryBae();//获取汇总商品
       })
     },
  
     changebalance(val,index){
        let chls = this.chlList[index];
        chls.BALTHISBAL = 1000;
        var num = Number(val.BALLASTBAL) + Number(val.BALTHISGETIN) - Number(val.BALTHISOUT) + Number(val.BALTAKEINVENTORY);
        Vue.set(this.chlList,index,{BALDPGID: val.BALDPGID,DPGNAME: val.DPGNAME,BALDEPOSIT: val.BALDEPOSIT,BALLASTBAL: val.BALLASTBAL,BALTHISGETIN: val.BALTHISGETIN,BALTHISOUT: val.BALTHISOUT,BALTHISFROZEN: val.BALTHISFROZEN,BALTAKEINVENTORY: val.BALTAKEINVENTORY,BALTHISBAL: num,BALREMARK: val.BALREMARK,isware:val.isware});
      },
      check(val,index) {
        let chl = this.chlList[index];  
        chl.HSHCOSTPRICE = this.checkNumber(chl.HSHCOSTPRICE.toString());
        chl.HSHSALEPRICE = this.checkNumber(chl.HSHSALEPRICE.toString());
        chl.HSHCOST = this.checkNumber(chl.HSHCOST.toString());
        chl.HSHSALE = this.checkNumber(chl.HSHSALE.toString());
      },
      //只能输入正整数
      checkNumber(value) {
        value = value.replace(/\D/g, "").replace(/^0+(?=\d)/, "");
        if (value !== "") {
          if (value.substr(0, 1) === "0" && value.length === 2) {
            value = value.substr(1, value.length);
          }
        } else {
          value = 0;
        }
        return value;
      },
      //只能输入金额
      checkMoney(value) {
        //修复第一个字符是小数点 的情况.
        if (value !== "" && value.substr(0, 1) === ".") {
          value = "";
        }
        value = value.replace(/^0*(0\.|[1-9])/, "$1"); //解决 粘贴不生效
        value = value.replace(/[^\d.]/g, ""); //清除“数字”和“.”以外的字符
        value = value.replace(/\.{2,}/g, "."); //只保留第一个. 清除多余的
        value = value
          .replace(".", "$#$")
          .replace(/\./g, "")
          .replace("$#$", ".");
        value = value.replace(/^(\-)*(\d+)\.(\d\d).*$/, "$1$2.$3"); //只能输入两个小数
        if (value.indexOf(".") < 0 && value !== "") {
          //以上已经过滤，此处控制的是如果没有小数点，首位不能为类似于 01、02的金额
          if (value.substr(0, 1) === "0" && value.length === 2) {
            value = value.substr(1, value.length);
          }
        } else if (value === "") {
          value = 0;
        }
        return value;
      },
    
      //自定义筛选
      chaFilter(val) {
        this.chaList = JSON.parse(JSON.stringify(this.allCharge));
        if (val) {
          if (val.length > 0)
            this.chaList = this.allCharge.filter(item => {
              return (
                item.CHANAME.indexOf(val) > -1 ||
                item.CHADM.toLowerCase().indexOf(val.toLowerCase()) > -1
              );
            });
        }
      },
      //提交
      submit(checkout = false) {
        switch (this.order) {
          case ADD://新增
            this.dataAdd(checkout);
            break;
          default:
            break;
        }
      },
      dataAdd(){
        let chlList = JSON.parse(JSON.stringify(this.chlList));
        let data = JSON.parse(JSON.stringify(this.regInfo));
        if(this.regInfo.HSLSTARTDATE){
          data.BAESTARTDATE =  formatDate(this.regInfo.HSLSTARTDATE, "yyyyMMdd");
        };
        if(this.regInfo.HSLDATE){
          data.HSLDATE =  formatDate(this.regInfo.HSLDATE, "yyyyMMdd");
        };
        if (chlList.length > 0) {
          data.list_Hsh = chlList;
        }
        apiBase.DoService(data, apiBase.getApiAdress().Depot.CreateAshHsl, res => {    
          this.$message({
            type: "success",
            message: "新增成功!"
          });
          this.closeDialog();
          this.refreshData();
        });
      },
      closeDialog() {
        switch (this.order) {
          case ADD:
          case INFO:
            this.$refs.dialog.close();
            break;
          default:
            break;
        }
      },
      refreshData() {
        this.$emit("refreshData");
      },
    },
    mounted() {
      
    },
    created() {
       
    },
    //计算属性
    computed: {
     
    },
    
    watch: {
    
    },
    mounted() {
      
    },
    components: {
      sweetModal
    }
  };

</script>
